import React, { useEffect, useState } from 'react';
import { Button, Card, Modal, Form, Input, Table, message, Upload, Popconfirm } from 'antd'
import { PlusOutlined, LoadingOutlined, DeleteOutlined, FormOutlined } from "@ant-design/icons";
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { getAddBrand, getChangeBrandList, getDeleteBrandList, getTrademarkApi } from '@api/user/trademark'
import { records } from '@api/user/model/trademark'

type LayoutType = Parameters<typeof Form>[0]['layout'];
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

function Trademark() {
    // 数据数据
    const [records, getRecords] = useState<records[]>([])
    // 当前页数
    const [current, getCurrent] = useState<number>(1)
    // 每页条数
    const [pageSize, getPageSize] = useState<number>(5)
    // 总数
    const [total, getTotal] = useState<number>(0)
    // 图片
    const [imgFile, getImgFile] = useState<string>('')
    // 名字
    const [name, setName] = useState<string>('')
    // id
    const [id, getId] = useState<number>(0)
    // 上传图片的逻辑
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    // 下一页数据
    const onChange = (page: number, pageSize: number) => {
        getCurrent(page)
        getPageSize(pageSize)
    }
    // 收集数据
    const [from] = Form.useForm()
    // 控制对话框显示
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
        from.resetFields()
        setImageUrl('')
    };
    // 确认按钮
    const handleOk = async () => {
        setIsModalOpen(false);
        const value = from.getFieldsValue().brandName
        if (!id) {
            try {
                getImgFile('')
                await getAddBrand(value, imgFile as string)
                await getList()
                if (records.length === 5) {
                    getCurrent(current + 1)
                }
                message.success('添加成功', 2)
            } catch (e) {
                message.error('添加失败', 2)
            }
        } else {
            getImgFile('')
            await getChangeBrandList(value, imgFile as string, id)
            await getList()
            message.success('修改成功', 2)
            getId(0)
        }

    }
    const handleCancel = () => {
        setIsModalOpen(false);
    }
    const getList = async () => {
        const res = await getTrademarkApi(current, pageSize)
        getRecords(res.records)
        getCurrent(res.current)
        getTotal(res.total)
        getPageSize(res.size)
    }
    useEffect(() => {
        getList()
    }, [current, pageSize])

    const onFinish = () => {
        handleOk()
    }
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(url);
                getImgFile(info.file.response.data)
            });
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8}}>Upload</div>
        </div>
    );
    // 删除品牌
    const deleteBrand = (record: records) => {
        return async () => {
            try {
                await getDeleteBrandList(record.id as number)
                if (records.length === 1) {
                    getCurrent(current - 1)
                }
                await getList()
                message.success('删除成功')
            } catch (e) {
                message.error('删除失败')
            }
        }
    }
    // 修改品牌
    const modifyBrand = (record: records) => {
        return () => {
            setIsModalOpen(true);
            setName(record.tmName)
            setImageUrl(record.logoUrl)
            getId(record.id as number)
            getImgFile(record.logoUrl)
            from.setFieldsValue({
                brandName: record.tmName
            })

        }
    }
    const cancel = () => {
        message.error('取消成功');
    }
    const [formLayout] = useState<LayoutType>('horizontal');
    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '品牌名称',
            dataIndex: 'tmName',
            key: 'tmName',
        },
        {
            title: '品牌LOGO',
            key: 'logoUrl',
            render: (text: any, record: any) => {
                return <img src={record.logoUrl} style={{width: '100px', height: '60px'}} alt={''}/>
            }
        },
        {
            title: '操作',
            render: (text: any, record: any) => (
                <><Button type={'primary'} size={'small'} icon={<FormOutlined/>}
                          onClick={modifyBrand(record)}>修改</Button>
                    <Popconfirm
                        title='你确定要删除吗'
                        onConfirm={deleteBrand(record)}
                        onCancel={cancel}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type={'primary'} danger size={'small'} className={'m1'}
                                icon={<DeleteOutlined/>}
                        >删除</Button>
                    </Popconfirm>

                </>
            )


        },
    ];
    const layout = {
        labelCol: {span: 8},
        wrapperCol: {span: 16},
    };
    return (
        <Card>
            <Button type='primary' icon={<PlusOutlined/>} onClick={showModal}>添加</Button>
            <Table
                dataSource={records}
                style={{marginTop: 20}}
                columns={columns} rowKey={'id'}
                pagination={{
                    showQuickJumper: true,
                    position: ['bottomRight', 'bottomLeft'],
                    total: total,
                    current: current,
                    pageSizeOptions: [5, 10],
                    pageSize: pageSize,
                    showTotal: () => {
                        return <div>共{total}条数据</div>
                    },
                    onChange: onChange

                }}
            />
            <Modal closable={false}
                   visible={isModalOpen}

                   onCancel={handleCancel}
                   style={{top: 0}}
                   width={600}
                   footer={null}
            >
                <Form
                    name="basic"
                    {...layout}
                    layout={formLayout}
                    labelCol={{span: 4}}
                    autoComplete="off"
                    form={from}
                    onFinish={onFinish}

                >
                    <Form.Item
                        label="品牌名称"
                        name="brandName"
                        rules={[{required: true, message: '请输入品牌名称'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        label="上传logo"
                    >
                        <Upload
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}

                        >
                            {imageUrl ? <img src={imageUrl} style={{width: '100%'}} alt=''/> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 15, span: 16}}>
                        <Button onClick={() => {
                            setIsModalOpen(false);
                        }
                        }>
                            取消
                        </Button>
                        <Button htmlType="submit" className={'m1'} type={'primary'}>
                            确认
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </Card>
    );
}

export default Trademark;